from flask import Blueprint, request,jsonify
from db import db
from utils.comm import gain_data,qntoken
import time,json,math

add = Blueprint('tabl',__name__)


def xtree(data):
    if not data:    # 判断data没有的话直接返回
        return data
    tree = {}
    list = []
    for i in data:
        tree[i['id']] = i
    
    for j in data:
        # 获取父id
        pid = j['pid']
        if pid == 0:
            # 是顶级分类直接加入列表
            list.append(j)
        else:
            # 查看父类下有没有子类
            if 'son' not in tree[pid]:
                # 如果没有初始化子类
                tree[pid]['son'] = []
            # 把子类加到父类列表
            tree[pid]['son'].append(j)
    return list

# 添加分类
@add.route("/cates",methods = ['POST','GET'])
def tab():
    if request.method == 'POST':
        gain = gain_data()
        print(gain)
        if gain['params']:
            sql = """
                insert into cates value (0,'%s',%d,%s)
            """%(gain['name'],int(gain['pid']),gain['params'])
            db.insert(sql)
            return jsonify({'code':200})
        else:
            sql = """
                insert into cates value (0,'%s',%d,'%s')
            """%(gain['name'],int(gain['pid']),gain['params'])
            db.insert(sql)
            return jsonify({'code':200})
    elif request.method == 'GET':
        sql = """
            select *from cates
        """
        res = db.findall(sql)
        print("************8")
        print(res)
        data = xtree(res)
        return jsonify({'code':200,'matter':data})

# 获取所有分类
@add.route('/pagecates')
def pagecates():
    sql = "select * from cates"
    # sql = "select c.name,c.params,t.name as tname from cates as c left join cates as t on c.pid=t.id order by c.id desc"
    res = db.findall(sql)
    # print("****************")
    # print(res)
    return jsonify({"code":200,'list':res})


# 获取教师信息
@add.route('/teacher')
def teacher():
    sql = """
        select *from teacher
    """
    time.sleep(1)
    res = db.findall(sql)
    print("?????????????????//")
    print(res)
    return jsonify({'code':200,'matter':res})


#通过分类id获取分类参数
@add.route('/getCateByid')
def getCateByid():
    id = request.args.get('id')
    sql = "select params from cates where id=%d"%(int(id))
    res = db.find(sql)
    return jsonify({'code':200,'params':res['params']})

#添加展示课程接口
@add.route('/courseM',methods=['POST','GET'])
def courseM():
    if request.method == 'POST':
        data = gain_data()
        if data['params']:
            sql = "insert into courses values(0,'%s',%d,'%s','%s','%s',%d,%d)"%(data['title'],int(data['pid']),data['params'],data['pic'],data['descrip'],int(data['teacher_id']),int(data['status']))
        else:
            sql = "insert into courses(title,pid,pic,descrip,teacher_id,status) values('%s',%d,'%s','%s',%d,%d)"%(data['title'],int(data['pid']),data['pic'],data['descrip'],int(data['teacher_id']),int(data['status']))
    
        db.insert(sql)
        return jsonify({"code":200})
    else:
        page = request.args.get('page')
        page_size = 2
        start = (int(page)-1)*page_size
        sql = """
            select c.title,c.pic,ca.name from courses as c left join cates as ca on c.pid=ca.id limit %d,%d 
        """%(start,page_size)
        res = db.findall(sql)
        sql1 = """
            select count(id)from courses
        """
        count = db.find(sql1)
        return jsonify({'code':200,'matter':res,'count':count})

# 获取课程
@add.route('/show_courses')
def show():
    page = int(request.args.get('page'))
    page_size = int(request.args.get('page_size'))
    start = (int(page)-1)*page_size
    sql = """
        select *from courses limit %d,%d 
    """%(start,page_size)
    res = db.findall(sql)
    sql1 = """
        select count(id)from courses
    """
    count = db.find(sql1)
    print(count)
    total = math.ceil(count['count(id)']/page_size)
    return jsonify({'code':200,'matter':res,'count':total})

@add.route('/show_cou',methods=['POST','GET'])
def show_courses():
    if request.method=='POST':
        pass
    else:
        id = request.args.get("id")
        sql = """
            select *from courses as c inner join teacher as t on c.teacher_id=t.id where id=%d 
        """%(int(id))
        res = db.findall(sql)
        print(res)
        return jsonify({"code":200,'matter':res})
